package com.neuedu.his.controller;

import com.neuedu.his.po.*;
import com.neuedu.his.service.MedicalrecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/medical-record")
public class MedicalRecordController {

    @Autowired
    private MedicalrecordService medicalRecordService;

    @PostMapping("/save")
    public ResponseEntity<?> saveMedicalRecord(@RequestBody MedicalRecordRequest request,
                                               @RequestHeader("doctorId") Integer doctorId) {
        // 验证请求数据
        if (request.getMedicalRecord() == null || request.getDiagnoses() == null || request.getAction() == null) {
            return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "请求参数不完整"
            ));
        }

        // 在服务层验证医生权限
        Map<String, Object> result = medicalRecordService.saveMedicalRecord(
                request.getMedicalRecord(),
                request.getDiagnoses(),
                request.getAction(),
                doctorId
        );

        if ((Boolean) result.get("success")) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body(result);
        }
    }

    @GetMapping("/get/{registId}")
    public ResponseEntity<?> getMedicalRecord(@PathVariable Integer registId,
                                              @RequestHeader("doctorId") Integer doctorId) {
        try {
            Map<String, Object> result = medicalRecordService.getMedicalRecordWithDiagnoses(registId, doctorId);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                    "message", e.getMessage(),
                    "success", false
            ));
        }
    }

    public static class MedicalRecordRequest {
        private Medicalrecord medicalRecord;
        private List<Medicaldisease> diagnoses;
        private String action;

        public Medicalrecord getMedicalRecord() {
            return medicalRecord;
        }

        public void setMedicalRecord(Medicalrecord medicalRecord) {
            this.medicalRecord = medicalRecord;
        }

        public List<Medicaldisease> getDiagnoses() {
            return diagnoses;
        }

        public void setDiagnoses(List<Medicaldisease> diagnoses) {
            this.diagnoses = diagnoses;
        }

        public String getAction() {
            return action;
        }

        public void setAction(String action) {
            this.action = action;
        }
    }
}